<template>
  <div>
    <search-cirteria />
    <div class="table-container">
      <table-operate>
        <n-button
          size="small"
          type="primary"
          @click="handleShowModal"
        >
          <template #icon>
            <n-icon :component="AddSharp" />
          </template>
          新增
        </n-button>
      </table-operate>
      <data-table
        :row-key="(row: Menu) => row.menuId"
        :columns="columns"
        :data="list"
        :loading="loading"
      />
    </div>
    <modal-form
      v-model:show="visible"
      title="菜单管理"
      :config="menuFormConifg"
      :width="550"
      :height="480"
      v-model:form="form"
      @confirm="handleConfirm"
      @cancel="handleCancel"
    />
  </div>
</template>

<script lang="ts" setup>
  import { NButton, useMessage, NFlex, NIcon, useDialog } from 'naive-ui'
  import { AddSharp } from '@vicons/ionicons5'
  import SearchCirteria from '@/components/SearchCriteria/index.vue'
  import TableOperate from '@/components/TableOperate/index.vue'
  import ModalForm from '@/components/ModalForm/index.vue'
  import TableButton from '@/components/TableButton/index.vue'
  import DictTag from '@/components/DictTag/index.vue'

  import { addMenu, getMenuList, deleteMenu, getMenu, updateMenu } from '@/api/power/menu'
  import { ListToTree, ListToTreeOption } from '@/utils/tool'

  import type { Menu } from '@/api/power/menu'
  import type { ModalFormConfig } from '@/components/ModalForm/index.vue'
  import type { DataTableColumns, TreeSelectOption } from 'naive-ui'

  import dayjs from 'dayjs'
  import { useDict } from '@/hooks/useDict'

  const { sys_menu_type } = useDict('sys_menu_type')

  const message = useMessage()
  const dialog = useDialog()
  const loading = ref(false)
  // 窗口显示/隐藏
  const visible = ref(false)

  const form = ref<Menu>({
    menuType: 1,
    visible: '1',
    sort: 0,
    status: '1'
  })

  // 显示新增窗口
  const handleShowModal = (id: any) => {
    if (typeof id === 'number') {
      getMenu(id).then(res => {
        form.value = res.data
      })
    }
    visible.value = true
  }

  const handleShowAdd = (id: number) => {
    form.value.parentId = id
    visible.value = true
  }

  // 确认保存
  const handleConfirm = async () => {
    const { menuId, ...arg } = form.value
    const newArgs: any = Object.assign({}, arg)
    menuFormConifg.value.forEach(i => {
      if (!i.show) newArgs[i.key] = null
    })

    if (menuId) {
      await updateMenu(menuId, newArgs)
      message.success('修改菜单成功')
    } else {
      await addMenu(newArgs)
      message.success('新增菜单成功')
    }

    handleCancel()
    handleSearch()
  }

  // 取消保存
  const handleCancel = () => {
    form.value = {
      menuType: 1,
      visible: '1',
      sort: 0,
      status: '1'
    }
    visible.value = false
  }

  const list = ref<Menu[]>([])
  const menuOptions = ref<TreeSelectOption[]>([])
  // 搜索
  const handleSearch = async () => {
    try {
      loading.value = true
      const res = await getMenuList()
      const tree = ListToTree(res.data, 'menuId')
      menuOptions.value = ListToTreeOption(
        res.data,
        row => row.menuId,
        row => row.menuName
      )
      console.log(menuOptions.value)
      list.value = tree
      loading.value = false
    } catch (err) {
      loading.value = false
    }
  }

  onMounted(() => {
    handleSearch()
  })

  function handleDelete(id: number) {
    dialog.warning({
      title: '提示',
      content: '是否确定删除数据？',
      positiveText: '确认',
      negativeText: '取消',
      onPositiveClick: async () => {
        await deleteMenu(id)
        message.success('删除成功')
        handleSearch()
      }
    })
  }

  const columns: DataTableColumns<Required<Menu>> = [
    {
      title: '菜单名称',
      key: 'menuName',
      width: 350
    },
    {
      title: '菜单类型',
      key: 'menuType',
      render: row => h(DictTag, { options: sys_menu_type.value, value: row.menuType })
    },
    {
      title: '组件路径',
      key: 'component'
    },
    {
      title: '权限标识',
      key: 'permission',
      width: 160
    },
    {
      title: '排序',
      key: 'sort'
    },
    {
      title: '创建时间',
      key: 'createTime',
      render: row => dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss')
    },
    {
      title: '操作',
      key: 'actions',
      width: 300,
      render(row) {
        return h(
          NFlex,
          { justify: 'center' },
          {
            default: () => [
              h(
                TableButton,
                {
                  type: 'primary',
                  icon: AddSharp,
                  onClick: () => handleShowAdd(row.menuId)
                },
                {
                  default: () => '新增'
                }
              ),
              h(
                TableButton,
                {
                  type: 'primary',
                  onClick: () => handleShowModal(row.menuId)
                },
                {
                  default: () => '修改'
                }
              ),
              h(
                TableButton,
                {
                  type: 'error',
                  onClick: () => handleDelete(row.menuId)
                },
                {
                  default: () => '删除'
                }
              )
            ]
          }
        )
      }
    }
  ]

  const menuFormConifg = ref<ModalFormConfig[]>([
    {
      type: 'tree-select',
      label: '父级菜单',
      key: 'parentId',
      span: 24,
      options: menuOptions,
      show: true
    },
    {
      type: 'input',
      label: '菜单名称',
      key: 'menuName',
      show: true
    },
    {
      type: 'radio',
      label: '状态',
      key: 'status',
      show: true,
      options: [
        { label: '启用', value: '1' },
        { label: '禁用', value: '0' }
      ]
    },
    {
      type: 'input',
      label: '路由路径',
      key: 'route',
      show: true
    },

    {
      type: 'input-number',
      label: '排序',
      key: 'sort',
      show: true
    },
    {
      type: 'radio',
      label: '菜单类型',
      key: 'menuType',
      show: true,
      options: [
        { label: '目录', value: 0 },
        { label: '菜单', value: 1 },
        { label: '按钮', value: 2 }
      ]
    },
    {
      type: 'radio',
      label: '显示状态',
      key: 'visible',
      show: true,
      options: [
        { label: '显示', value: '1' },
        { label: '隐藏', value: '0' }
      ]
    },
    {
      type: 'input',
      label: '权限标识',
      key: 'permission',
      show: computed(() => form.value.menuType === 1 || form.value.menuType === 2)
    },
    {
      type: 'input',
      label: '组件路径',
      key: 'component',
      show: computed(() => form.value.menuType === 1)
    }
  ])
</script>

<style scoped lang="scss"></style>
